var express = require('express');
var router = express.Router();
var request = require('request');
var async = require('async');
var logger = require('../logger');
var superagent = require('superagent');
var jwt = require('jsonwebtoken');
var mongo = require('mongoskin');
var http = require("http");
var fs = require("fs");
var redis = require("redis");
var client = redis.createClient(6379,"127.0.0.1");
const UA_List = require('../controllers/UA_List');

var db = mongo.db("mongodb://localhost:27017/weGDUT");
db.bind('weGDUT');



/**
 * 功能:api识别验证码
 * @param {char} Imgurl 
 */

function yzmRecognize( Imgurl )
{
    var Imgurl = __dirname + '/.' +  Imgurl
    var options = { 
        method: 'POST',
        url: 'http://119.29.102.251:88/upload/',
        headers: { 
            'cache-control': 'no-cache',
            'content-type': 'multipart/form-data' },
        formData: {
             yzm: fs.createReadStream(Imgurl)}
        };
   return new Promise((resolve,reject) => {
        request(options, function (error, response, body) {
        if (error) throw new Error(error);
        // console.log(body);
        resolve(body)
        });
    })
}



/**
 * 功能：保存验证码图片并返回路径,cookie
 */
function getYZM(){
    //TODO 获取并保存验证码图片
    var date = Date.now()
    var rand = GetRandomNum()
    var param = date + rand
    var url = "http://jxfw.gdut.edu.cn/yzm?d=" + param
    return new Promise((resolve, reject)=>{
        http.get(url, function(res){
		var imgData = "";
		// console.log(res.headers['set-cookie'])
		let cookie = res.headers['set-cookie'];
        res.setEncoding("binary"); //一定要设置response的编码为binary否则会下载下来的图片打不开

        res.on("data", function(chunk){
            imgData+=chunk;
        });

        res.on("end", function(){
            var saveUrl = "./public/yzm/"+param+".jpeg";
            fs.writeFile(saveUrl, imgData, "binary", function(err){
                if(err){
                    console.log(err);
                    console.log("down fail");
                }else{
					console.log('save yzm successfully');
					//resolve(saveUrl)
                    resolve({"saveUrl":saveUrl,"cookie":cookie})
                }
                });
            });
        });
    })
}


async function sendYZM(req, res, next){
    // TODO 获取并保存验证码图片
    var proxy = await getRandomProxy();
    // console.log(proxy)
    var date = Date.now()
    var rand = GetRandomNum()
    var param = date + rand
    var url = "http://jxfw.gdut.edu.cn/yzm?d=" + param
   
    var headers =  {
        "content-type": "application/x-www-form-urlencoded",
        "cache-control": "no-cache",            
        'User-Agent': UA_List.get()
    };
    // console.log(headers);
    var yzmurl = 'https://wegdut.yoricklee.com/yzm/'+param+'.jpg';
    superagent
        .get(url)
        .set(headers)
        // .proxy(proxy)
        .end((err, resp) => {
            if (err) {
                console.log(err)
            } else {
                let saveUrl = "./public/yzm/"+param+".jpg";
                fs.writeFile(saveUrl, resp.body, 'binary', (err, result) =>{
                    console.log('ok')
                })
                // console.log(resp);
                let cookie = resp.headers['set-cookie'];
                res.send({code:200, message:'ok', data:{url:yzmurl,cookie:cookie} });
            }
        }) 
    // // console.log(option);
    //     http.request(options, function(response){
	// 	var imgData = "";
	// 	console.log(response)
	// 	let cookie = response.headers['set-cookie'];
    //     response.setEncoding("binary"); //一定要设置response的编码为binary否则会下载下来的图片打不开

    //     response.on("data", function(chunk){
    //         imgData+=chunk;
    //     });

    //         fs.writeFile(saveUrl, imgData, "binary", function(err){
    //             if(err){
    //                 console.log(err);
    //                 console.log("down fail");
    //             }else{
	// 				console.log('save yzm successfully');
    //                 //resolve(saveUrl)
                    
    //                 res.send({code:200, message:'ok', data:{url:yzmurl,cookie:cookie} })
    //             }
    //             });
    //         });
    //     });
}

function getRandomProxy()
 {
     return new Promise((resolve, reject) => {
        client.spop('proxy', (err, reply) => {
            if (err) {
                console.log(err);
            } else {
                resolve(reply);
            }
        });
    });
 }

/**
 * 获取cet4/6查询验证码
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */

function getCetYzm(req, res, next){
    //TODO 获取并保存验证码图片
    var id = Math.random()
    var rand = GetRandomNum(1000,9999)
    var param = id + rand
    var url = "http://www.chsi.com.cn/cet/ValidatorIMG.JPG?ID=" + param
        http.get(url, function(response){
        var imgData = "";
        // console.log(response.headers)
        // console.log("cookie1:"+response.headers['set-cookie'][1])
        var cookie = response.headers['set-cookie'];  
        // 赋值可用的cookie      
        if(cookie.length==2){
            cookie = cookie[1]
            console.log('2')
        }else{
            cookie = cookie[0];
        }
        // console.log('cookie after :'+cookie)
		
        response.setEncoding("binary"); //一定要设置response的编码为binary否则会下载下来的图片打不开

        response.on("data", function(chunk){
            imgData+=chunk;
        });

        response.on("end", function(){
            var saveUrl = "./public/cetyzm/"+param+".jpg";
            fs.writeFile(saveUrl, imgData, "binary", function(err){
                if(err){
                    console.log(err);
                    console.log("down fail");
                }else{
					console.log('save yzm successfully');
                    //resolve(saveUrl)
                    var yzmurl = 'https://wegdut.yoricklee.com/cetyzm/'+param+'.jpg'

                    res.send({code:200, message:'ok', data:{url:yzmurl,cookie:cookie} })
                }
                });
            });
        });
}

/**
 * 功能:获取随机数,默认3位
 * @param {*} Min 
 * @param {*} Max 
 */
function GetRandomNum(Min=100,Max=999)
{   
    var Range = Max - Min;   
    var Rand = Math.random();   
    return(Min + Math.round(Rand * Range));   
}   
/**
 * 根据范围产生随机数
 * @param {*} Max 
 * @param {*} Min 
 */
function randomNum(Max, Min=0) {
    var Range = Max - Min;   
    var Rand = Math.random();   
    return(Min + Math.round(Rand * Range));  
}
/**
 * 存用户cookie到redis
 * @param {char} username 
 * @param {char} cookie 
 */
function setCookieIntoRedis(username, cookie)
{   
    return new Promise((resolve, reject) => {
        let input = {username:username, cookie:cookie}        
        let d = new Date()
        input.created_time = d.getTime()
        client.HMSET('cookie:'+username, input, function(err,res){
            if (err) {
                console.log(err)
            }
        });
        //一小时过期
        client.expire('cookie:'+username, 3600,(err, reply) => {
            if (err) {
                console.log(err)
            } else {
                resolve(reply)
            }
        });
    });
}

/**
 * 返回cookie，不存在则为0
 * @param {char} username 
 */
function getCookieFromRedis(username)
{
  return new Promise((resolve, reject) => {
    client.HMGET('cookie:' + username,'cookie',function(error, res){
       if(error){
				console.log('redis error:'+error)
			 }else{
				// console.log('redis hget:'+res)
                var cookie = res
				if(cookie){
					resolve(cookie)
				}else{
				   //redis不存在cookie则返回0
				   resolve(0)
				}
       }
    })
  })
}

module.exports = { yzmRecognize, getYZM, getCookieFromRedis, setCookieIntoRedis, sendYZM, getCetYzm};
